﻿Imports System.IO
Imports System.Net
Imports System.Security.Cryptography.X509Certificates


Public Class Output

    Private _Trades As Generic.List(Of Trade)
    Public Property Trades() As Generic.List(Of Trade)
        Get
            Return _Trades
        End Get
        Set(ByVal value As Generic.List(Of Trade))
            _Trades = value
        End Set
    End Property

#Region "Public Methods"

    Sub CreateMT300(ByVal AllTrades As Generic.List(Of Trade))
        Me.Trades = AllTrades
        Dim iTotalTrades, iRunCount, iFileNumber As Integer
        Dim bHeader As Boolean = True

        Try


            For Each myTrade As Trade In Me.Trades
                With myTrade
                    Using swMT300 As New IO.StreamWriter(My.Application.Info.DirectoryPath & "\MT300_Upload" & iFileNumber & ".txt", True) 'Open uplWriter to write to MT300 file
                        If bHeader Then

                            swMT300.WriteLine("300")                  'Write the MT300 Header
                            swMT300.WriteLine("FromBic" & Chr(9) & "ToBic" & Chr(9) & "New Sequence 15A" & Chr(9) & "Sender's Reference" _
                            & Chr(9) & "Related Reference" & Chr(9) & "Type of operation" & Chr(9) & "Scope of operation" & Chr(9) & "Common Reference" _
                            & Chr(9) & "Block Trade Indicator" & Chr(9) & "Split Settlement" & Chr(9) & "Party A" & Chr(9) & "Party B" & Chr(9) _
                            & "Fund or Beneficiary" & Chr(9) & "Terms and Conditions" & Chr(9) & "New Sequence 15B" & Chr(9) & "Trade Date" _
                            & Chr(9) & "Value Date" & Chr(9) & "Exchange Rate" & Chr(9) & "CurrencyAmount Bought" & Chr(9) & "Delivery Agent" _
                            & Chr(9) & "Intermediary" & Chr(9) & "Receiving Agent" & Chr(9) & "CurrencyAmount Sold" & Chr(9) & "Delivery Agent" _
                            & Chr(9) & "Intermediary" & Chr(9) & "Receiving Agent" & Chr(9) & "Beneficiary Institution" & Chr(9) & "New Sequence 15C" _
                            & Chr(9) & "Contact Information" & Chr(9) & "Dealing Branch Party A" & Chr(9) & "Dealing Branch Party A" & Chr(9) & _
                            "Dealing Branch Party B" & Chr(9) & "Broker Id" & Chr(9) & "Broker's Commission" & Chr(9) & "Counterparty's Reference" _
                            & Chr(9) & "Broker's Reference" & Chr(9) & "Sender to Receiver" & Chr(9) & "New Sequence 15D" & Chr(9) & _
                            "Buy/Sell Indicator" & Chr(9) & "Currency,Amount" & Chr(9) & "Delivery Agent" & Chr(9) & "Intermediary" & _
                            Chr(9) & "Receiving Agent" & Chr(9) & "Beneficiary Institution" & Chr(9) & "Number of settlements")
                            bHeader = False

                        End If
                        iRunCount += 1
                        If .Fund.IsNoneMapped OrElse .Broker Is Nothing Then Continue For

                        'swith from given/counter to buy/sell
                        Dim sBuyCCY, sBuyAmt, sSellCCY, sSellAmt As String

                        If .Side = String.Empty OrElse .Side Is Nothing OrElse .Side.ToLower = "buy" Then
                            sBuyCCY = .GivenCCY
                            sBuyAmt = Me.PrepAmt(.GivenAmt, .GivenCCY)
                            sSellCCY = .CounterCCY
                            sSellAmt = Me.PrepAmt(.CounterAmt, .CounterCCY)
                        Else
                            sBuyCCY = .CounterCCY
                            sBuyAmt = Me.PrepAmt(.CounterAmt, .CounterCCY)
                            sSellCCY = .GivenCCY
                            sSellAmt = Me.PrepAmt(.GivenAmt, .GivenCCY)
                        End If

                        swMT300.WriteLine(My.Settings.sBIC & Chr(9) & .Broker.BrokerBIC & Chr(9) & "15A" & Chr(9) & .ClientID & Chr(9) & Chr(9) & _
                        .Operation & Chr(9) & Chr(9) & GetCommonRef(myTrade) & Chr(9) & Chr(9) & Chr(9) & My.Settings.sBIC & Chr(9) & .Broker.BrokerBIC & _
                         Chr(9) & Chr(9) & String.Format("{0:yyyyMMdd}", .FixingDate) & Chr(9) & "15B" & Chr(9) & String.Format("{0:yyyyMMdd}", .TradeDate) & _
                         Chr(9) & String.Format("{0:yyyyMMdd}", .ValueDate) & Chr(9) & PrepAmt(.AllInRate) & Chr(9) & sBuyCCY & sBuyAmt & Chr(9) & _
                         .SSIs.BSDeliveryAgent & Chr(9) & .SSIs.BSIntermediary & Chr(9) & .SSIs.BSReceivingAgent & Chr(9) & sSellCCY & sSellAmt & _
                         Chr(9) & .SSIs.SSDeliveryAgent & Chr(9) & .SSIs.SSIntermediary & Chr(9) & .SSIs.SSReceivingAgent & _
                         Chr(9) & .SSIs.SSBeneficiary & Chr(9) & "15C" & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & _
                         .SenderToReceiver & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & Chr(9) & "-")

                        iTotalTrades += 1

                        If iTotalTrades > 499 OrElse iTotalTrades = Me.Trades.Count Then
                            swMT300.WriteLine("<<" & iTotalTrades & ">>")
                            bHeader = True
                            iFileNumber += 1

                        End If

                    End Using
                End With
            Next
        Catch ex As Exception
            frmLoader.LoaderError.LogError(ex, "CreateMT300")
        End Try
    End Sub

    Sub UploadToGTSS()
        Dim sMT300s As String()
        Dim sSearchPattern As String = "*" & My.Settings.sFileMask & "*"
        If sSearchPattern = "**" Then sSearchPattern = "*.*"

        Try
            If My.Settings.bFileUploadOnly Then
                sMT300s = Directory.GetFiles(My.Settings.sInputDir, sSearchPattern, SearchOption.TopDirectoryOnly)
            Else
                sMT300s = Directory.GetFiles(My.Application.Info.DirectoryPath & "\", "*MT300*")
            End If

            If My.Settings.bAutoUpload AndAlso Me.Trades.Count > 0 Then
                Dim gtssUp As New GTSSFileWebService.FileWebService

                For Each sMT300 As String In sMT300s
                    With gtssUp

                        .Credentials = New NetworkCredential(My.Settings.sInsitution & "." & My.Settings.sUserID, My.Settings.sPW)
                        .CookieContainer = New CookieContainer

                        'handle different connection types
                        If My.Settings.bConnectLTS Then
                            .Url = "http://" & My.Settings.sLTSIP & "/gtss/service/FileWebService"
                        Else
                            Dim cookGTSS As New Cookie("SMCHALLENGE", "YES")
                            cookGTSS.Domain = My.Settings.sGTSSURL

                            If Not My.Settings.sProxyPort = String.Empty OrElse My.Settings.sProxyPort IsNot Nothing Then
                                Dim iProxyPort As Integer = Convert.ToInt32(My.Settings.sProxyPort)
                                Dim sProxy As New System.Net.WebProxy(My.Settings.sProxy, iProxyPort)
                                .Proxy = sProxy
                            End If

                            Dim cCert As X509Certificate2
                            If My.Settings.sCertPW = String.Empty Then
                                cCert = New X509Certificate2(My.Settings.sCertPath)
                            Else
                                cCert = New X509Certificate2(My.Settings.sCertPath, My.Settings.sCertPW)
                            End If
                            .ClientCertificates.Add(cCert)

                        End If

                        Dim upRequest As New GTSSFileWebService.UploadFileRequestType
                        Dim response As GTSSFileWebService.UploadResponseType
                        Dim sFile As String

                        Using objReader As New System.IO.StreamReader(sMT300)
                            sFile = objReader.ReadToEnd
                            objReader.Close()
                        End Using

                        upRequest.fileData = sFile

                        If My.Settings.sFileUploadType = String.Empty OrElse My.Settings.sFileUploadType Is Nothing Then
                            upRequest.fileType = "TabDelimMT300"
                        Else
                            upRequest.fileType = My.Settings.sFileUploadType

                        End If


                        response = .UploadFile(upRequest)
                        If response.result = "Successful" Then
                            Logger.MsgLog("Trades uploaded to GTSS Successfully")
                        Else
                            Logger.MsgLog("Error uploading trades: " & response.result)
                        End If
                    End With
                Next
            End If

        Catch ex As Exception
            frmLoader.LoaderError.LogError(ex, "Output")
            End
        End Try
    End Sub

    Sub Archive()
        Dim sInputFiles As String() = Directory.GetFiles(My.Settings.sInputDir)

        If My.Settings.bFileUploadOnly = False Then
            'archive mt300s
            Dim sMT300s As String() = Directory.GetFiles(My.Application.Info.DirectoryPath & "\", "*MT300*")
            Dim sMT300ArchiveDir As String = My.Application.Info.DirectoryPath & "\MT300Archive"
            If Not Directory.Exists(sMT300ArchiveDir) Then Directory.CreateDirectory(sMT300ArchiveDir)

            For Each sMT300 As String In sMT300s
                File.Copy(sMT300, sMT300ArchiveDir & "\" & Path.GetFileNameWithoutExtension(sMT300) & String.Format("{0:yyyyMMddhhmmss}", Now()) & Path.GetExtension(sMT300))
                File.Delete(sMT300)
            Next

        End If

        Dim sArchiveDir As String = My.Application.Info.DirectoryPath & "\Archive"
        If Not Directory.Exists(sArchiveDir) Then Directory.CreateDirectory(sArchiveDir)
        For Each sFile In sInputFiles
            'If My.Settings.bDeleteArchives = False Then File.Copy(sFile, sArchiveDir & "\ExportFile\" & String.Format("{0:yyyyMMddhhmmss}", Now()) & Path.GetExtension(sFile))
            'File.Delete(sFile)
        Next


    End Sub

#End Region


#Region "Private Methods"

    Private Function GetCommonRef(ByVal myTrade As Trade) As String
        GetCommonRef = Nothing
        'puts together a common reference for the MT300 file
        Dim sRate As String = myTrade.AllInRate
        sRate = Replace(sRate, ",", "")

        Do Until Right(sRate, 1) <> "0"
            If Right(sRate, 1) = "0" Then
                sRate = sRate.Remove(sRate.Length - 1)
            End If
        Loop

        Do Until sRate.Length > 3
            If sRate.Length < 4 Then
                sRate = "0" & sRate
            End If
        Loop

        sRate = Right(sRate, 4)

        GetCommonRef = Left(My.Settings.sBIC, 6) & sRate & Left(myTrade.Broker.BrokerBIC, 6)

    End Function

    Private Function PrepAmt(ByVal Amount As Double, Optional ByVal CCY As String = "") As String
        'removes decmimal, adds comma, ints JPY trades, and absolutes everything

        Amount = Math.Abs(Amount)

        If CCY = "JPY" Then
            Return Int(Amount)
        Else
            Return Amount.ToString.Replace(".", ",")
        End If

    End Function
#End Region

End Class
